package org.comparator4j.comparator;

import java.util.AbstractCollection;
import java.util.Iterator;

import org.comparator4j.Comparator;
import org.comparator4j.CompareContext;
import org.comparator4j.CompareException;

public class AbstractCollectionComparator implements Comparator {

	@SuppressWarnings("unchecked")
	public Result compare(Object o1, Object o2, CompareContext context)
			throws CompareException {
		if (o1 instanceof AbstractCollection
				&& o2 instanceof AbstractCollection) {
			int o1Length = AbstractCollection.class.cast(o1).size();
			int o2Length = AbstractCollection.class.cast(o2).size();
			if (o1Length > o2Length) {
				return Result.GT;
			} else if (o1Length < o2Length) {
				return Result.LT;
			} else {
				Iterator ito1 = AbstractCollection.class.cast(o1).iterator();
				Iterator ito2 = AbstractCollection.class.cast(o2).iterator();
				for (int i = 0; i < o1Length; i++) {
					Object o1i = ito1.next();
					Object o2i = ito2.next();
					Result r = context.newCompareContext().compare(o1i, o2i);
					if (r != Result.EQ) {
						return r;
					}
				}
				return Result.EQ;
			}
		}
		return context.compare(o1, o2);
	}
}
